package com.project.common.core.utils.yzs;

import com.alibaba.fastjson.JSONException;
import com.project.common.core.config.prop.PropAttributes;
import com.project.common.core.config.prop.PropConfig;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 云知声接口
 *
 * @Author: wyy
 * @Date: 2020-07-30 17:32
 */
public class YzsUtils {

    /**
     * 云知声API地址
     */
    public static final String VOICE_TEST = "http://edu.hivoice.cn:8085/eval/mp3";

    /**
     * 日志工具
     */
    public static final Logger log = LoggerFactory.getLogger(YzsUtils.class);

    /**
     * 云知声语音评测
     */
    /**
     * @param heandParams 头参数
     * @param text        内容
     * @param filePath    公网地址
     * @return
     * @throws Exception
     */
    public static HttpResponse httppost(Map<String, String> heandParams, String text, String filePath) throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(VOICE_TEST);
        MultipartEntity customMultiPartEntity = new MultipartEntity();
        HttpResponse response = null;
        try {
            //添加post参数
            customMultiPartEntity.addPart("text", new StringBody(text, Charset.forName("UTF-8")));
            customMultiPartEntity.addPart("mode", new StringBody("E", Charset.forName("UTF-8")));

            byte[] bytes = IOUtils.toByteArray(new URL(filePath));

            String[] fileNameArr = filePath.split("\\.");
            String fileNameSuffix = fileNameArr[fileNameArr.length - 1];
            String sourcePath = PropConfig.getProperty(PropAttributes.NFS__SERVICE_FILE_SHARE_PATH) + "/" + RandomStringUtils.randomAlphanumeric(18) + "." + fileNameSuffix;
            FileUtils.writeByteArrayToFile(new File(sourcePath), bytes);
            ContentBody fileBody = new FileBody(new File(sourcePath));

            customMultiPartEntity.addPart("voice", fileBody);
            httpPost.setEntity(customMultiPartEntity);

            //添加头部参数
            for (Map.Entry<String, String> entry : heandParams.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

            response = client.execute(httpPost);
        } catch (JSONException e) {
            log.error("云知声测评报错");
            System.err.println(e);
        }
        return response;
    }
}
